package stackoverflow.domain.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import stackoverflow.domain.service.UserService;
import stackoverflow.domain.user.User;
import stackoverflow.domain.user.UserRepository;
import stackoverflow.domain.user.UserUtility;

@Service("userServiceImpl")
public class UserServiceImpl implements UserService {
	private UserRepository userRepository;

	// User Assembler is used to separate out the logic for spring's UserDetailsService
	private UserAssembler userAssembler;
	
	@Autowired
	public UserServiceImpl(
			@Qualifier("userRepositoryImpl") UserRepository userRepository,
			@Qualifier("userAssemblerImpl") UserAssembler userAssembler) {
		this.userRepository = userRepository;
		this.userAssembler = userAssembler;
	}

	public User createNewUser(String userName, String password) {
		User newUser = UserUtility.createNewUser(userName, password);
		userRepository.add(newUser);
		return newUser;
	}

	public User getUser(String userId) {
		return null;
	}

	public boolean isLoggedIn(String userId) {
		return false;
	}

	public void login(String userId) {
	}

	public void logout(String userId) {
		User user = userRepository.find(userId);
	}

	/*
	 * This method is required to satisfy the UserDetailsService interface from Spring security.
	 */
	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException 
	{
	    UserDetails userDetails = null;
	    stackoverflow.domain.user.User applicationUserEntity = userRepository.findByName(username);
	    if (applicationUserEntity == null)
	      throw new UsernameNotFoundException("user not found");
	
	    return userDetails = userAssembler.buildUserFromUserEntity(applicationUserEntity);
	}

	public User createNewUser() {
		// TODO Auto-generated method stub
		return null;
	}
}
